package com.interview.javabase.classsload;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author: zsg
 * @description: 自定义的类加载器
 * @date: 2019/6/22 19:16
 * @modified:
 */
public class MyClassLoader extends ClassLoader {

    private String path;

    private String className;

    public MyClassLoader(String path,String className) {
        this.path = path;
        this.className = className;
    }

    @Override
    protected Class<?> findClass(String name) {
        byte[] b = getByteData(name);
        return defineClass(name, b, 0, b.length);
    }

    private byte[] getByteData(String name) {
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;

        try {
            inputStream = new FileInputStream(path + name + ".class");
            byteArrayOutputStream = new ByteArrayOutputStream();

            // 拷贝.class的话一次读取1byte才能完美复制
            int bytes;
            while ((bytes = inputStream.read()) != -1) {
                byteArrayOutputStream.write(bytes);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                byteArrayOutputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return byteArrayOutputStream.toByteArray();
    }
}
